<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/11/21
 * Time: 10:49 AM
 */

namespace Biz\module\Decoupling\order;

use Biz\module\Decoupling\AbstractMain;
use Biz\service\Event;
use Biz\service\salesRebate\SalesOrder as sSalesOrder;
use Biz\service\Stock as sStock;
use Biz\service\trade\Integral as sIntegral;
use Biz\service\trade\Pay;
use Doraemon\pockets\constInterface\AppType;
use Doraemon\tools\Log as tLog;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderOperateLog as mOrderOperateLog;
use Doraemon\amqp\Queue as aQueue;
use Biz\service\Group as sGroup;
use Biz\service\redPacket\RedPackets as sRedPackets;
use Biz\service\settlement\SettlementTransaction as sSettlementTransaction;

class CancelOrder extends AbstractMain
{

    const NAME = '取消订单的异步任务';

    public function main($message, $data)
    {
        $appendData = [
            'eventId' => $data['header']['event_id'],
            'uid' => $data['body']['uid'],
            'addTime' => $data['header']['addtime'],
            'orderNo' => $data['body']['order_no'],
            'isSys' => $data['body']['is_sys'],
            'reasonId' => $data['body']['reason_id'],
        ];

        $appendData['orderInfo'] = mOrder::getOrderInfo($appendData['orderNo']);

        $this->appendData($appendData);

    }

    protected function _exec_stock_incro()
    {
        //回滚库存
        $result = sStock::IncrStockByOrderNos([$this->data['orderNo']]);

        if($result === false){
            return false;
        }

        $this->appendLog('成功回滚库存', $this->data);
    }

    protected function _exec_stock_incro_after_sent_event(){

        //取消订单回滚库存的事件
        $result = Event::push(Event::ORDER_CANCEL_STOCK_DECR_SUCCESS, [
            'uid' => $this->data['uid'],
            'order_no' => $this->data['orderNo'],
            'is_sys' => (int)$this->data['isSys'],
            'uniq_idx' => ['order_no', 'event_tag']
        ], $this->data['eventId']);

        $this->appendLog('成功下发回滚库存事件', $this->data);

        return $result;

    }

    protected function _exec_operate_integral()
    {
        if ($this->data['orderInfo']['integral'] > 0) {
            //退积分
            sIntegral::operatePoint($this->data['orderInfo']['uid'], $this->data['orderInfo']['integral'], $this->data['orderNo'], 3);

            $this->appendLog('回滚积分成功', $this->data);

        }
    }

    protected function _exec_operate_integral_after_send_event(){

        //取消订单回滚积分的事件
        $result = Event::push(Event::ORDER_CANCEL_INTEGRAL_SUCCESS, [
            'uid' => $this->data['uid'],
            'order_no' => $this->data['orderNo'],
            'integral' => $this->data['orderInfo']['integral'],
            'integral_amount' => $this->data['orderInfo']['integral_amount'],
            'is_sys' => (int)$this->data['isSys'],
            'uniq_idx' => ['order_no', 'event_tag']
        ], $this->data['eventId']);

        return $result;
    }

    protected function _exec_close_order()
    {
        Pay::closeOrder($this->data['orderNo']);

        $this->appendLog('关闭订单的支付通道成功', $this->data);

    }

    protected function _exec_notice_pintuan(){
        try{
            if ($this->data['orderInfo']['order_type'] != mOrder::ORDER_TYPE_PING_TUAN){
                return true;
            }
            sGroup::delGroup($this->data['orderNo']);

            $this->appendLog('取消订单时回调给拼团', $this->data);

        }catch (\Exception $e){
            $this->appendLog('取消订单时回调给拼团 出现异常', [
                "sGroup::delGroup" => [
                    $this->data['orderNo'],
                ],
                "e_msg" => $e->getMessage(),
                "e_line" => $e->getLine(),
                "e_file" => $e->getFile()
            ]);
            throw $e;

        }
    }

    protected function _exec_for_salesrebate(){

        try {
            sSalesOrder::afterCloseOrder($this->data['orderNo'],2);

            $this->appendLog('关闭订单时回调设计师返利计划', array_merge($this->data));

        }catch (\Exception $e){
            $this->appendLog('关闭订单时回调设计师返利计划 出现异常', [
                "sSalesOrder::afterCloseOrder" => [
                    $this->data['orderNo'],
                    2
                ],
                "e_msg" => $e->getMessage(),
                "e_line" => $e->getLine(),
                "e_file" => $e->getFile()
            ]);
            throw $e;
        }
    }

    protected function _exec_order_operate_log()
    {
        //取消理由
        $reasonDesc = '';
        if ($this->data['reasonId'] > 0) {
            $reasonDesc = sprintf("   取消理由:%s", mOrder::$cancelReasonDesc[$this->data['reasonId']]);
        }

        //交易记录日志
        $result = mOrderOperateLog::createLog( $this->data['orderInfo']['shop_id'], $this->data['orderNo'], mOrderOperateLog::TRADE_TYPE_ORDER, $opLog = [
            'operate_user_type' => $this->data['isSys'] ? mOrderOperateLog::OPERATE_USERTYPE_SYS : mOrderOperateLog::OPERATE_USERTYPE_USER,
            'operate_uid' => $this->data['isSys'] ? 0 : $this->data['uid'],
            'operate_type' => $this->data['isSys'] ? mOrderOperateLog::OPERATE_TYPE_AUTO_CANCEL_ORDER : mOrderOperateLog::OPERATE_TYPE_CANCEL_ORDER
        ], '', $this->data['isSys'] ? '超时自动取消订单' : '用户手动取消订单' . $reasonDesc, '', [], $this->data['addTime']);

        $this->appendLog('记录交易日志成功', array_merge($this->data, $opLog));

        if(is_object($result) && $result->rowCount() > 0){
            return true;
        }

        return false;
    }

    protected function _exec_redpackets_cancel(){
        try{
            if($this->data['orderInfo']['packet_amount'] <=0){
                return true;
            }
            sRedPackets::cancelInOrder($this->data['uid'],$this->data['orderNo'],$this->data['orderInfo']['packet_amount']);

        }catch (\Exception $e){
            $this->appendLog('红包取消失败', [
                "sRedPackets::cancelInOrder" => [
                    $this->data['uid'],
                    $this->data['orderNo'],
                    $this->data['orderInfo']['packet_amount']
                ],
                "e_msg" => $e->getMessage(),
                "e_line" => $e->getLine(),
                "e_file" => $e->getFile()
            ]);
            throw $e;
        }
    }


}